package cs4280.ass2.admin.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;

import cs4280.ass2.entity.Member;
import cs4280.ass2.entity.Officer;
import cs4280.ass2.entity.User;
import cs4280.ass2.exception.ValidateException;
import cs4280.ass2.persistence.OfficerDao;
import cs4280.ass2.util.UserUtils;

public class OfficerNewAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String START_DATE_FORMAT = "dd/MM/yyyy";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.sendRedirect(req.getContextPath()+ "/admin/officer/new.jsp");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String login = StringUtils.trim(req.getParameter("login"));
		String password = StringUtils.trim(req.getParameter("password"));
		String firstName = StringUtils.trim(req.getParameter("firstName"));
		String lastName = StringUtils.trim(req.getParameter("lastName"));


		Officer officer = new Officer();
		officer.setLogin(login);
		officer.setPassword(password);
		officer.setFirstName(firstName);
		officer.setLastName(lastName);
		officer.setAppUserStatus(User.APP_USER_ACTIVE);
		officer.setType(User.USER_TYPE_OFFCIER);
		officer.setCreateDate(new Date());
		officer.setCreateUser(0);
		officer.setModifyDate(new Date());
		officer.setModifyUser(0);

		try {
			UserUtils.validate(officer);
			OfficerDao.getInstance().registerOfficer(officer);
			req.setAttribute("message.info", "message.info.officer.addsuccess");
			getServletContext().getRequestDispatcher("/admin/officer/list.do").forward(req, resp);
		} catch (ValidateException e) {
			req.setAttribute("message.error", e.getMessage());
			getServletContext().getRequestDispatcher("/admin/officer/new.jsp").forward(req, resp);
		}

	}
}
